﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using HXDNB.Model;
using System.Web.Mvc;
using HXDNB.Infrastructure.Helper;
using System.Web;
namespace HXDNB.DAL
{
    public class MeunBLL : IDisposable
    {
        readonly Entities _e = new Entities();

        /// <summary>
        /// 根据ID查询单个栏目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Meun Get(int id)
        {
            var info = (from i in _e.Meuns where i.ID == id select i).SingleOrDefault();
            return info;
        }


        /// <summary>
        /// 查询所有一级栏目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<Meun> GetParents()
        {
            var info = (from i in _e.Meuns where i.ParentId == 0 select i).ToList();
            return info;
        }
        /// <summary>
        /// 根据ID查询父级栏目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Meun GetParent(int id)
        {
            var info = (from i in _e.Meuns
                        join j in _e.Meuns on i.ParentId equals j.ID
                        where i.ID == id
                        select j).SingleOrDefault();
            return info;
        }

        /// <summary>
        /// 查询菜单列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public IQueryable<MeunListModel> GetList(string name)
        {
            var list = from i in _e.Meuns select i;
            if (string.IsNullOrWhiteSpace(name) == false)
            {
                list = from i in list where i.Name.Contains(name) select i;
            }
            var newlist = from i in list
                          join j in _e.Meuns on i.ParentId equals j.ID into M
                          from j in M.DefaultIfEmpty()
                          orderby i.UpdateTime descending
                          select new MeunListModel { ID = i.ID, EName = i.EName, Name = i.Name, MeunName = j.Name ?? "顶级栏目", CreateTime = i.CreateTime, UpdateTime = i.UpdateTime, IsRelease = i.IsRelease };
            return newlist;
        }

        /// <summary>
        /// 根据父级栏目ID获取子栏目列表
        /// </summary>
        /// <returns></returns>
        public List<Meun> GetSonMeuns(int parentID)
        {
            var list = (from i in _e.Meuns
                        where i.ParentId == parentID
                        select i).ToList();
            if (parentID == 0 && HttpContext.Current.Session["MeunRole"] != null)
            {
                list = list.Where(i => HttpContext.Current.Session["MeunRole"].ToString().Contains("," + i.ID + ",")).ToList();
            }
            list = list.OrderBy(i => i.Sort).ToList();
            return list;
        }

        /// <summary>
        /// 获取排序后的栏目菜单
        /// </summary>
        /// <returns></returns>
        public void GetALLSort(int startID, ref List<Meun> list)
        {
            var meuns = GetSonMeuns(startID);
            foreach (var item in meuns)
            {
                list.Add(item);
                GetALLSort(item.ID, ref list);
            }
        }

        /// <summary>
        /// 根据子栏目ID获取至顶级栏目列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="list"></param>
        /// <returns></returns>
        public void GetParentList(int id, ref List<Meun> list)
        {
            if (list == null) return;
            var m = Get(id);
            list.Add(m);
            if (m.ParentId == 0)
            {
                list.Reverse();
            }
            else
            {
                GetParentList(m.ParentId ?? 0, ref list);
            }
        }
        /// <summary>
        /// 获取绑定到下拉框中的栏目列表
        /// </summary>
        /// <returns></returns>
        public List<SelectListItem> GetListItem()
        {
            List<Meun> list = new List<Meun>();
            List<SelectListItem> listItem = new List<SelectListItem>();
            GetALLSort(0, ref list);
            foreach (var item in list)
            {
                var parentlist = new List<Meun>();
                GetParentList(item.ID, ref parentlist);
                var text = new StringBuilder();
                for (int i = 0; i < parentlist.Count; i++)
                {
                    if (i == parentlist.Count - 1)
                        text.Append(parentlist[i].Name);
                    else
                        text.AppendFormat("{0} > ", parentlist[i].Name);
                }
                listItem.Add(new SelectListItem { Text = text.ToString(), Value = item.ID.ToString() });
            }
            return listItem;
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(Meun model)
        {
            string err = null;
            model.CreateTime = DateTime.Now;
            model.UpdateTime = DateTime.Now;
            model.IsRelease = "N";
            try
            {
                _e.Meuns.AddObject(model);
                _e.SaveChanges();
            }
            catch (Exception e)
            {
                err = e.Message;
                model.ID = 0;
            }
            finally
            {
                string msg = string.Format("添加栏目[ID:{0},名称:{1}]", model.ID, model.Name);
                new LogBLL().Add(LogType.栏目日志, msg, model.ID > 0, err);
            }
            return model.ID;//添加成功返回自增ID        
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Edit(Meun model)
        {
            bool result = false;
            string err = null;
            model.UpdateTime = DateTime.Now;
            model.IsRelease = "N";
            try
            {
                var info = Get(model.ID);
                if (info != null)
                {
                    model.CreateTime = info.CreateTime;
                    _e.Meuns.Detach(info);
                    _e.Meuns.Attach(model);
                    _e.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "栏目不存在";
                }
            }
            catch (Exception e)
            {
                err = e.Message;
                result = false;
            }
            finally
            {
                string msg = string.Format("编辑栏目[ID:{0},名称:{1}]", model.ID, model.Name);
                new LogBLL().Add(LogType.栏目日志, msg, result, err);
            }
            return result;
        }

        /// <summary>
        /// 根据ID删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            bool result = false;
            string err = null;
            var info = Get(id);
            try
            {
                if (info != null)
                {
                    _e.Meuns.DeleteObject(info);
                    result = _e.SaveChanges() > 0;
                }
                else
                {
                    err = "栏目不存在";
                }
            }
            catch (Exception e)
            {
                result = false;
                err = e.Message;
            }
            finally
            {
                string msg = string.Format("删除栏目[ID:{0},名称:{1}]", id, (info ?? new Meun()).Name);
                new LogBLL().Add(LogType.栏目日志, msg, result, err);            }
            return result;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}
